function nmat = readmidi(fn)
% function nmat = readmidi(fn)
%
% Conversion of MIDI file to notematrix
%
% Input:
%	fn   [str] - Filename of the MIDI file to convert
%
% Output:
%	nmat [mat] - The notematrix
%

% Change History :
% Date		Time	Prog	Note
% 11.8.2002	18:36	PT	Created under MATLAB 5.3 (Macintosh)
% 2.1.2003	13:12	TE	Created under MATLAB 5.3 (PC)
% Part of the MIDI Toolbox, Copyright 2004, University of Jyvaskyla, Finland
% See License.txt
%
% Modified 02/03/2010 by Graham Grindlay (grindlay@ee.columbia.edu) to
% ensure compatibility with 64-bit linux installations (these require
% ia32-libs or similar to execute the 32-bit t2mf.GLNX86 binary).

% Copyright (C) 2010-2030 Graham Grindlay (grindlay@ee.columbia.edu)
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

nmat=[];

if strcmp(computer,'MAC2')
	currdir = cd;
	currdir = char(bitand(double(currdir),255)); % remove high bytes that occasionally occur in the path
	toolboxpath = which('readmidi');
	toolboxpath=toolboxpath(1:end-11); % remove ':readmidi.m'
	cd(toolboxpath);
	fid = fopen('mf2t.param','wt');

	ifile = [currdir ':' fn];
	fprintf(fid, '%s\n', ifile);
	ofile = [toolboxpath ':mf2t.out']; 
	fprintf(fid, '%s\n', ofile);
	fclose(fid);
	! mf2tmac
	delete mf2t.param
	nmat = mftxt2nmat(ofile);
	cd(currdir);
elseif strcmp(computer,'PCWIN')
	midi2text(fn, 'MF2T.OUT'); % uusin mex konvertteri [2. tammikuuta 2003] 
	nmat = mftxt2nmat('MF2T.OUT');
	delete mf2t.out
	clear mex    
elseif strcmp(computer,'GLNX86') || strcmp(computer, 'GLNXA64')
    % Use actual shell command  2004-08-13 dpwe@ee.columbia.edu
	of = [tempname,'.txt'];
	cmd = [miditoolboxpath,'/mf2t.GLNX86 ',fn,' ',of];
	disp(cmd);
	system(cmd);
	nmat = mftxt2nmat(of);
	delete(of)
elseif strcmp(computer, 'MAC')
    % Use actual shell command  2004-08-13 dpwe@ee.columbia.edu
	of = [tempname,'.txt'];
	cmd = [miditoolboxpath,'/mf2t.',computer,' ',fn,' ',of];
	disp(cmd);
	system(cmd);
	nmat = mftxt2nmat(of);
	delete(of)
else
	disp('This function works only on Macintosh (OS X), Windows and Linux!');
	return;
end